/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lansupportserver;

import lansupportserver.LanSupportServer;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Quan
 */
public class GlobalListener implements Runnable {
    
    private lansupportserver.LanSupportServer lanSupportServer;
    
    public GlobalListener(lansupportserver.LanSupportServer lanSupportServer) {
        this.lanSupportServer = lanSupportServer;
    }
    
    @Override
    public void run() {
        try {
            ServerSocket serverSocket = new ServerSocket(LanSupportServer.serverPort);
            while (true) {
                Integer new_port = (int) (Math.random() * 10000);
                Socket connection = serverSocket.accept();
                
                this.SendMesager(connection, new_port.toString());
                Runnable only1ClientListen = new Only1ClientListener(lanSupportServer, new_port, connection.getInetAddress());
                Thread thread = new Thread(only1ClientListen);
                thread.start();
            }
        } catch (IOException ex) {
            Logger.getLogger(LanSupportServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private void SendMesager(Socket socket, String mesages) throws IOException {
        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
        OutputStreamWriter osw = new OutputStreamWriter(bos, "UTF-8");
        osw.write(mesages + (char) LanSupportServer.CloseNumber);
        osw.flush();
    }
}
